<?php

namespace app\middleware;

use app\common\JwtTool;
use think\Response;
use think\Request;

/**
 * jwt中间件
 */
class JwtAuth
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        // Authorization Bearer xxxxxxxxxxxx

        $header = $request->header('authorization');

        if (!$header) {
            return json([
                'code' => 401,
                'msg' => '未提供token'
            ],401);
        }

        // 提取Bearer Token
        if (!preg_match('/Bearer\s(\S+)/', $header, $matches)) {
            return json([
                'code' => 401,
                'msg' => 'token格式错误'
            ],401);
        }

        $token = $matches[1];

        try {
            // 解析Token
            $payload = JwtTool::decode($token);

            // 将用户信息附加到请求对象上
            $request->user = (object)$payload;

            // 验证通过，继续执行后续逻辑
            return $next($request);

        } catch (\Exception $e) {
            // Token无效、过期等
            return json([
                'code' => 401,
                'msg' => 'token无效或已过期'
            ],401);
        }
    }
}